<template>
  <view class="common-bg">
    <view class="pad-20">
      <uni-nav-bar :border="false" color="#222" backgroundColor="transparent" left-icon="left" leftText="" title=""
        @clickLeft="clickLeft" @clickRight="clickRight"
        :right-text="showMask ? $t('mine.cancel') : $t('manage.manageText')" />
      <view class="title m-t-40 font-24 col-000-8 font-600">
        {{detail.collection_name}}
      </view>
      <view class="font-14 col-000-4 m-t-8">
        {{detail.pattern_count}}{{ $t('mine.pattern') }}
      </view>
      <view class="btn-box m-t-40">
        <view class="left flex-center-center" @click="playAll">
          <image class="img" src="/static/svg/play.svg" mode="widthFix"></image>
          <view class="col-fff font-14 font-500">
            <!-- 播放全部 -->
						{{$t('manage.playAll')}}
          </view>
        </view>
        <view class="right shadow flex-center-center" @click="playAllSj()">
          <image style="width: 32rpx;height: 28rpx;" src="/static/svg/suiji.svg" mode="widthFix"></image>
        </view>
      </view>
      <view class="list-box">
        <view class="item shadow" v-for="(item, index) in patterns" :key="index">
          <view class="mask" v-if="showMask" @click="doChoose(index)">
            <view class="choose flex-center-center" :class="{ 'on': item.choose }">
              <uni-icons v-if="item.choose" type="checkmarkempty" color="#fff" size="18"></uni-icons>
            </view>

          </view>
          <view class="b flex-center-center">
            <image class="img" :src="item.preview_image" mode="widthFix"></image>
          </view>
          <view class="foot flex flex-between flex-center	">
            <view class="font-14 col-000-8 ell">
              {{ item.pattern_name }}
            </view>
            <view class="add flex-center-center" @click="addPlay(item.id)">
              <uni-icons type="plusempty" color="rgba(0,0,0, 0.4)" size="20"></uni-icons>
            </view>
          </view>
        </view>
      </view>
      <view class="set-footer-zan">

      </view>
      <view class="set-footer">
        <uni-transition ref="ani" custom-class="transition" :mode-class="modeClass" :show="showMask">
          <view class="foot pad-0-20">
            <view class="left font-12 col-000-4">
              {{ ids.length }} {{ $t('manage.Selected') }}
            </view>
            <view class="center" @click="add">
              <uni-icons type="plusempty" size="20" color="rgba(0,0,0,0.8)"></uni-icons>
              <!-- 添加到播放列表 -->

              {{ $t('manage.addToPlayList') }}
            </view>
            <view class="right flex-content-center4" @click="del">
              <image class="remove" src="/static/svg/remove.svg" mode="widthFix"></image>
              {{ $t('manage.remove') }}
            </view>
          </view>
        </uni-transition>
      </view>
    </view>
    <!-- 立即播放全部 -->
    <selectDevice ref="ref_select_device" @choose="chooseDevice" />
    <!-- 添加一首到播放列表 -->
    <selectDevice ref="ref_select_device_one" @choose="chooseDeviceOne" />
    <!-- 随机播放 -->
    <selectDevice ref="ref_select_device_sj" @choose="chooseDeviceSj" />

  </view>
</template>

<script>
import uniNavBar from '@/uni_modules/uni-nav-bar/components/uni-nav-bar/uni-nav-bar.vue';
import collectionApi from '@/api/collection.js';
import playlistApi from '@/api/playlist.js';
import selectDevice from '@/components/select-device/index.vue'
export default {
  data() {
    return {
      addPatternId: '',// 记录添加的id
      collectionId: '',
      modeClass: 'fade',
      showMask: false,
      ids: [],
			patterns: [],
			detail: {
				collection_name: ''
			}
    }
  },
  components: {
    uniNavBar,
    selectDevice,
  },
	created() {
		// this.getDetail()
	},
	onPullDownRefresh() {
		this.getDetail()
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 1000);
	},
  methods: {
    chooseDeviceOne(sns) {
      let deviceSn = sns.length == 1 ? sns[0] : sns;
      playlistApi.batchAddPatternsToEnd({
        deviceSn: deviceSn,
        patternIds: [this.addPatternId]
      }).then(res => {
        if(res.errCode === 0) {
          this.addPatternId = '';
          uni.showToast({
            title: res.errMsg,
            icon: 'none',
            duration: 3000
          });
          this.$refs.ref_select_device.closePopup()
        }
      })

    },
    chooseDevice(sns) {
      let deviceSn = sns.length == 1 ? sns[0] : sns;
      let patternIds = this.patterns.map(item => item.id)
      playlistApi.batchAddPatternsToEnd({
        deviceSn: deviceSn,
        patternIds
      }).then(res => {
        if(res.errCode === 0) {
          uni.showToast({
            title: res.errMsg,
            icon: 'none',
            duration: 3000
          });
          this.$refs.ref_select_device.closePopup()
        }
      })
    },
    chooseDeviceSj(sns) {
			let patternIds = this.patterns.map(item => item.id)
		let params = {
			deviceSn: sns.length == 1 ? sns[0] : sns,
        patternIds,
        playMode: '1' // 随机播放模式
		}
		// 先播放所有图案
		playlistApi.playNow(params).then(res => {
			if(res.errCode === 0) {
				// 然后设置为随机播放模式
				return playlistApi.updatePlayMode({
					deviceSn: sns.length == 1 ? sns[0] : sns,
					playMode: '1' // 1=随机播放
				})
			}
		}).then(res => {
				if(res && res.errCode === 0) {
					uni.showToast({
					  title: '随机播放模式已设置',
					  icon: 'none',
					  duration: 3000
					});
          this.$refs.ref_select_device_sj.closePopup()
				}
			})
		},
		onLoad(option) {
			const collection_id = option?.collection_id || '';
			this.collectionId = collection_id;
			if(!collection_id) {
				uni.showToast({
					title: this.$t('common.parameterError'),
					icon: 'none',
					duration: 3000
				});
				return;
			}
			this.getDetail(collection_id);
		},

		getDetail(collection_id = null) {
      this.ids = [];
			const collectionId = collection_id || this.collectionId;
      this.collectionId = collectionId;
			if(!collectionId) {
				uni.showToast({
					title: this.$t('common.parameterError'),
					icon: 'none',
					duration: 3000
				});
				return;
			}
			collectionApi.getCollectionDetail({
				collection_id: collectionId
			}).then(res => { 
        if(res.errCode === 0) {
					Object.assign(this.detail, res.data); // 合并赋值
					this.patterns = res.data.patterns;
				}
			}).catch(err => {
				uni.showToast({
					title: err.errMsg,
					icon: 'none',
					duration: 3000
				});
			})

		},
    add() {
      console.log(this.ids)
			if(this.ids.length == 0) {
			  uni.showToast({
			    // title: '请选择要添加的图案',
			    title: this.$t('manage.selectPattern'),
			    icon: 'none',
			    duration: 3000
			  });
			  return;
			}
			let params = {
				deviceId: this.collectionId,
				patternIds: this.ids
			}
			playlistApi.batchAddPatternsToEnd(params).then(res => {
			  if(res.errCode === 0) {
			    uni.showToast({
			      title: this.$t('manage.playAllSuccess'),
			      icon: 'none',
			      duration: 3000
			    })
			  } else {
			    uni.showToast({
			      title: res.errMsg,
			      icon: 'none',
			      duration: 3000
			    })
			  }
			})
    },
    del() {
      if(this.ids.length == 0) {
        uni.showToast({
          title: this.$t('manage.selectPatternToRemove'),
          icon: 'none',
          duration: 3000
        });
        return;
      }
      console.log(this.ids)
      let params = {
        collection_id: this.collectionId,
        pattern_id: this.ids.join(',')
      }
      collectionApi.removePatternFromCollection(params).then(res => {
        if(res.errCode === 0) {
          uni.showToast({
            title: this.$t('manage.removeSuccess'),
            icon: 'none',
            duration: 3000
          })
          this.clickRight()
          this.getDetail()
        } else {
          uni.showToast({
            title: res.errMsg,
            icon: 'none',
            duration: 3000
          })
        }
      })
    },
    clickLeft() {
      uni.navigateBack()
    },
    clickRight() {
      this.showMask = !this.showMask;
      if (this.showMask) {
        this.patterns.forEach(item => {
          item.choose = false
        })
        this.ids = []
      } else {
        // 关闭管理模式时也清空选中
        this.patterns.forEach(item => {
          item.choose = false
        })
        this.ids = []
      }
    },
    doChoose(index) {
      if(this.patterns[index].choose) {
        this.patterns[index].choose = false;
      } else {
        this.patterns[index].choose = true;
      }
      let ids = this.patterns.filter(item => item.choose).map(item => item.id)
      this.ids = ids;
    },
    addPlay(id) {
      this.addPatternId = id;// 记录添加的id
      this.$refs.ref_select_device_one.open()
      return
			let params = {
				deviceId: this.collectionId,
				patternId: id
			}
      playlistApi.addPattern(params).then(res => {
        if(res.errCode === 0) {
          uni.showToast({
            title: this.$t('manage.addedToPlayList'),
            icon: 'none',
            duration: 3000
          })
        } else {
          uni.showToast({
            title: res.errMsg,
            icon: 'none',
            duration: 3000
          })
        }
      })
    },
    playAll() {
			this.$refs.ref_select_device.open()
    },
    playAllSj() {
      this.$refs.ref_select_device_sj.open()
    }
  }
}
</script>

<style lang="scss" scoped>
.set-footer-zan {
  width: 100%;
  height: 106rpx;
}

.set-footer {
  width: 100%;
  height: 96rpx;
  position: fixed;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 10;
  background-color: #fff;
  box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.4);

  .foot {
    width: 100%;
    height: 96rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .remove {
    width: 32rpx;
    height: 32rpx;
    margin-right: 8rpx;
  }

  .right {
    color: #EB4839;
  }
}

.list-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 40rpx;

  .item {
    width: 316rpx;
    height: 412rpx;
    overflow: hidden;
    margin-bottom: 40rpx;
    position: relative;

    .mask {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      background-color: rgba(0, 0, 0, 0.30);
      z-index: 10;

      .choose {
        width: 56rpx;
        height: 56rpx;
        background: rgba(0, 0, 0, 0.3);
        border: 1px solid #FFFFFF;
        border-radius: 100%;
        position: absolute;
        right: 24rpx;
        top: 24rpx;

        &.on {
          background: #000000;
          border: 1px solid #000;
        }
      }
    }

    .b {
      width: 100%;
      height: 316rpx;
      background-color: rgba(216, 216, 216, 1);

      .img {
        width: 276rpx;
        height: 276rpx;
        border-radius: 100%;
      }
    }

    .foot {
      padding: 24rpx 24rpx 32rpx;

      .add {
        width: 56rpx;
        height: 56rpx;
        border-radius: 100%;
        border: 1rpx solid rgba(0, 0, 0, 0.08);
      }
    }
  }
}

.btn-box {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .left {
    width: 550rpx;
    height: 100rpx;
    background: #000000;
    border-radius: 16rpx;

    .img {
      width: 35rpx;
      height: 35rpx;
      margin-right: 20rpx;
    }
  }

  .right {
    width: 100rpx;
    height: 100rpx;
  }
}
.ell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;

}
</style>